package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.wanho.entity.Student;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author：汤小洋
 * Date：2025-02-12 14:51
 * Description：<描述>
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/doc")
@Slf4j
public class DocController {

    private final ElasticsearchRestTemplate restTemplate;

    /**
     * 创建文档
     */
    @RequestMapping("/create")
    public String create(){
        restTemplate.save(new Student(1006, "陈八", 18, "男", "清华大学"));
        return "success";
    }

    /**
     * 批量添加
     */
    @RequestMapping("/batch")
    public String batch(){
        List<Student> list = new ArrayList<>();
        list.add(new Student(1001, "张三", 18, "男", "清华大学"));
        list.add(new Student(1002, "李四", 19, "女", "北京大学"));
        list.add(new Student(1003, "王五", 20, "男", "南京大学"));
        list.add(new Student(1004, "赵六", 21, "女", "浙江大学"));
        list.add(new Student(1005, "孙七", 22, "男", "上海大学"));
        restTemplate.save(list);
        return "success";
    }

    /**
     * 查询id查询
     */
    @GetMapping("/{id}")
    public Student findById(@PathVariable String id){
        Student stu = restTemplate.get(id, Student.class);
        return stu;
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public List<Student> findAll(){
        SearchHits<Student> hits = restTemplate.search(Query.findAll(), Student.class);

        System.out.println("数量：" + hits.getTotalHits());
        List<Student> students = hits.stream()
                .map(hit -> hit.getContent())
                .collect(Collectors.toList());

        return students;
    }

    /**
     * 条件查询
     */
    @GetMapping("/search/{school}/{minAge}/{maxAge}")
    public List<Student> search(@PathVariable String school, @PathVariable Integer minAge, @PathVariable Integer maxAge){

        // 记录日志
        log.info("开始执行search方法。。。。。。。。。。。。。。。。。。");

        // QueryBuilder queryBuilder = QueryBuilders.matchQuery("school", school);
        // QueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(minAge).lte(maxAge);

        // BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
        //         .must(QueryBuilders.matchQuery("school", school))
        //         .must(QueryBuilders.rangeQuery("age").gte(minAge).lte(maxAge));
        //
        // NativeSearchQuery query = new NativeSearchQuery(queryBuilder);

        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.rangeQuery("age").gte(minAge).lte(maxAge))
                .withSort(Sort.by(Sort.Direction.DESC, "age"))
                .withPageable(PageRequest.of(0,2))
                .withSourceFilter(new FetchSourceFilter(new String[]{"id","name","age"}, null))
                .build();

        SearchHits<Student> hits = restTemplate.search(query, Student.class);
        List<Student> students = hits.stream()
                .map(hit -> hit.getContent())
                .collect(Collectors.toList());

        try{
            int i = 5/0;
        }catch(Exception e){
            // 记录日志
            log.error("程序出问题啦。。。。。。。" + e.getMessage());
        }

        return students;
    }


}
